package com.cl.mybatis.learn.day02;

import java.beans.PropertyVetoException;
import java.io.IOException;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class Mybatis002 {
    public static void main(String[] args) throws IOException, PropertyVetoException {
        
        // 创建数据源
        PooledDataSource datasource = new PooledDataSource();
        datasource.setDriver("com.mysql.jdbc.Driver");
        datasource.setUrl("jdbc:mysql://zhoufei.ali.db.com:3306/test");
        datasource.setUsername("root");
        datasource.setPassword("root");
        
        // 事务
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        // 创建环境
        Environment environment = new Environment("development", transactionFactory, datasource);
        // 创建配置
        Configuration configuration = new Configuration(environment);
        
        // 加入资源（Mapper接口）
        configuration.addMapper(UserMapper.class);
        
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            User test1 = session.selectOne(UserMapper.class.getName() + ".selectById", 7);
            System.out.println("第一次：" + test1);
            User test2 = session.selectOne(UserMapper.class.getName() + ".selectById", 7);
            System.out.println("第二次：" + test2);
        } finally {
            session.close();
        }
    }
}
